package com.gnerv.oauth.service;

import com.gnerv.oauth.utils.GsonUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PushbackInputStream;
import java.lang.reflect.Type;
import java.util.stream.Collectors;

/**
 * 对加密的请求参数，解密
 *
 * @date 2018/10/10 11:35
 */
@ControllerAdvice
public class RequestBodyDecryptAdvice extends RequestBodyAdviceAdapter  {

	/**
	 * 前置拦截匹配操作(定义自己业务相关的拦截匹配规则)
	 * 满足为true的才会执行下面的方法
	 * 
	 * @date 2018/10/10 11:43
	 */
	@Override
	public boolean supports(MethodParameter methodParameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		boolean assignableFrom = StringHttpMessageConverter.class.isAssignableFrom(converterType);
		return true;
	}

	/**
	 * 对加密的请求参数，解密
	 * 
	 * @date 2018/10/10 12:55
	 */
	@Override
	public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		//对加密的请求参数，解密
		String s = GsonUtils.toJson(body);

		String jsonStrDecrypt = "";
		System.out.println("对加密的请求参数，解密："+ jsonStrDecrypt);
		return jsonStrDecrypt;
	}

	@Override
	public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
		InputStream body = inputMessage.getBody();
		String content = new BufferedReader(new InputStreamReader(inputMessage.getBody()))
				.lines().collect(Collectors.joining(System.lineSeparator()));
		return super.beforeBodyRead(inputMessage, parameter, targetType, converterType);
	}

	@Override
	public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
		return super.handleEmptyBody(body, inputMessage, parameter, targetType, converterType);
	}
}
